//
//  AFN.m
//
//  Created by dllo on 15/4/13.
//

#import "AFN.h"

@implementation AFN


+ (void)urlString:(NSString *)urlString getAFNdata:(GetAFN)getAFNdata
{
    
    
    NSString *url_string = [NSString stringWithString:urlString];
    
    // 设置AFN网络请求管理对象
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    // 设置响应解析对象
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/x-javascript",nil];
    
    //AFN的get 请求
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 请求的返回数据是NSData
        // 进行JSON 解析
        // 使用block 返回网络数据
        getAFNdata(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        // 如果请求失败, 返回失败信息
        
    }];
}


+ (void)GETwithAFNByURL:(NSString *)urlstr completion:(void (^)(id responseObject))block
{
    
    
#warning 添加本地缓存部分
    
    /*********************************/
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    /*********************************/
    
    
    // 网址转码 处理中文字符
    NSString *str = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 创建AFN网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 设置响应解析对象
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置数据支持类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil]];
    
#warning 添加本地缓存
    /*********************************/
    //本地缓存设置，沙盒路径设置
    NSArray *path =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    
    NSString *pathString =path.lastObject;
    
    NSString *pathLast =[NSString stringWithFormat:@"/Caches/com.hackemist.SDWebImageCache.default/%lu.text", (unsigned long)[str hash]];
    
    //创建字符串文件存储路径
    NSString *PathName =[pathString stringByAppendingString:pathLast];
    
    //第一次进入判断有没有文件夹，如果没有就创建一个
    NSString * textPath = [pathString stringByAppendingFormat:@"/Caches/com.hackemist.SDWebImageCache.default"];
    if (![[NSFileManager defaultManager]fileExistsAtPath:textPath]) {
        
        [[NSFileManager defaultManager]createDirectoryAtPath:textPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
    /*********************************/
    
    
    
    // AFN的GET请求
    //    [manager.requestSerializer setValue:@"JSESSIONID=mEB0pErmREFMb61XjxBsgA" forHTTPHeaderField:@"Cookie"];
    [manager GET    :str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 请求成功执行的地方
        // responseObject返回数据为NSData
        
        /*********************************/
        [netWorkManager stopMonitoring];
        /*********************************/
        
        if (responseObject) {
            // 如果返回数据不为空, 则开始JSON解析
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            // 通过block回调数据
            block(result);
            
            /*********************************/
            [responseObject writeToFile:PathName atomically:YES];
            
            /*********************************/
            
            
        } else {
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 请求失败执行的地方
        
        /*********************************/
        NSString * cachePath = PathName;
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) {
            
            
            //从本地读缓存文件
            NSData * data =[NSData dataWithContentsOfFile:cachePath];
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            // 通过block回调数据
            block(result);
            
        }
        /*********************************/
        
    }];
    
}

@end
